package com.weibo.service.impl;
import java.io.IOException;
import java.util.*;

import com.mysql.cj.xdevapi.JsonArray;
import com.weibo.dao.WeiboDetailDao;
import com.weibo.entity.WeibosParam;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSONObject;
import com.weibo.service.WeibodetailService;
import com.weibo.entity.WeiboDetail;
/**
 * WeiboDetail的服务接口的实现类
 * 
 * @author 
 *
 */
@Service
public class WeibodetailServiceImpl implements WeibodetailService {
	private final Logger LOG = LogManager.getLogger(this.getClass());

	@Autowired
	private WeiboDetailDao weiboDetailDao;
	// TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化
	private static final int C200 = 200;
	private static final int C412 = 412;
	public String resultFormat(int code, Object data) {
		JSONObject result = new JSONObject();
		result.put("code", code);
		if (data != null) {
			result.put("data", data);
		}
		return result.toJSONString();
	}

	@Override
	public List<WeiboDetail> find(WeiboDetail value) {
		//TODO这里可以做通过Assist做添加查询
		List<WeiboDetail> result = weiboDetailDao.selectWeiboDetailByObj(value);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行获取WeiboDetail数据集-->结果:", result);
		}
		return result;
	}
	@Override
	public WeiboDetail findOne(String id) {
		if (id == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行通过WeiboDetail的id获得WeiboDetail对象-->失败:id不能为空");
			}
			return null;
		}
		WeiboDetail result = weiboDetailDao.selectWeiboDetailById(id);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行通过WeiboDetail的id获得WeiboDetail对象-->结果:", result);
		}
		return result;
	}

	@Override
	public int saveNotNull(WeiboDetail value) {
		if (value == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行将WeiboDetail中属性值不为null的数据保存到数据库-->失败:对象不能为空");
			}
			return -1;
		}
		if(value.getUid() == null  ){
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行将WeiboDetail中属性值不为null的数据保存到数据库-->失败:存在不能为空的空值");
			}
			return -1;
		}
		int result = weiboDetailDao.insertNotNullWeiboDetail(value);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行将WeiboDetail中属性值不为null的数据保存到数据库-->结果:", result);
		}
		return result;
	}
	@Override
	public int updateNotNullById(WeiboDetail value) {
		if (value == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行通过WeiboDetail的id更新WeiboDetail中属性不为null的数据-->失败:对象为null");
			}
			return -1;
		}
		int result = weiboDetailDao.updateNotNullWeiboDetailById(value);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行通过WeiboDetail的id更新WeiboDetail中属性不为null的数据-->结果:", result);
		}
		return result;
	}

	@Override
	public int deleteById(String id) {
		if (id == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行通过WeiboDetail的id删除WeiboDetail-->失败:id不能为空");
			}
			return -1;
		}
		int result = weiboDetailDao.deleteWeiboDetailById(id);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行通过WeiboDetail的id删除WeiboDetail-->结果:", result);
		}
		return result;
	}

	@Override
	public int fetchWeibos(WeibosParam param) {




		return 0;
	}

	/*private Map dealPage(String containerid, int page, String sinceId) throws ParseException, IOException, InterruptedException{
		//分页大小设置得太多，返回的分页大小就会随机，55 57 75 都返回过。
		//String url = "https://m.weibo.cn/api/container/getIndex?count=25&page=" + page + "&containerid=" + containerid;
		String url ;
		if(null!=sinceId){
			url = "https://m.weibo.cn/api/container/getIndex?type=uid&value=" + WeiboIdToDataBase.id + "&containerid=" + containerid + "&since_id=" +sinceId;
		}else{
			url = "https://m.weibo.cn/api/container/getIndex?type=uid&value=" + WeiboIdToDataBase.id + "&containerid=" + containerid;
		}
		log.debug("打印url"+url);
		List<WeiboDetail> pics = new ArrayList<WeiboDetail>();
		HttpClient httpClient = getHttpClient();
		HttpGet get = new HttpGet(url);
		get.setHeader("User-Agent", USER_AGENT);
		get.setHeader("referer", "https://weibo.com/");
		JsonObject root;
		try {
			HttpResponse response = httpClient.execute(get);
			//log.info(response.toString());
			String ret = EntityUtils.toString(response.getEntity(), "utf-8");
			// 防封
			root = new JsonParser().parse(ret).getAsJsonObject();
			//log.info(ret.toString());
		} catch (Exception e) {
			log.error("解析json出现异常"+page);
			e.printStackTrace();
			try {
				Thread.sleep(2000);
				getImgURL(containerid, page,sinceId);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return null;
		}
		String since_id =null;

		JsonObject asJsonObject = root.getAsJsonObject("data");
		int ok = root.get("ok").getAsInt();
		Map result = new HashMap();
		//log.info(asJsonObject.toString());
		if(ok==0){
			log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
			Thread.sleep(5000);
			//过会重试
			return getImgURL(containerid, page,sinceId);
		}else if(ok==1){
			JsonObject cardlistInfo = asJsonObject.getAsJsonObject("cardlistInfo");
			if(null!=cardlistInfo){
				since_id = cardlistInfo.get("since_id").getAsString();
			}
			JsonArray array = asJsonObject.getAsJsonArray("cards");
			log.info("返回大小"+array.size());
			for (int i = 0; i < array.size(); i++) {
				JsonObject mblog = array.get(i).getAsJsonObject().getAsJsonObject("mblog");
				if (mblog != null) {
					String createAt = mblog.get("created_at").getAsString();
					String text = mblog.get("text").getAsString();
					//有bug 返回 1970-1-1
					String date = getDate(createAt);
					log.info("返回的微博日期"+date);
					if (WeiboIdToDataBase.needFilterDate) {
						if (date.compareTo(WeiboIdToDataBase.startTime) < 0 || date.compareTo(WeiboIdToDataBase.endTime) > 0){
							result.put("since_id",since_id);
							result.put("sum",array.size());
							//log.info("时间到了");
							//return result;
							continue;
						}
						if(WeiboIdToDataBase.filterWords.length>0 && contains(text, WeiboIdToDataBase.filterWords) ){
							continue;
						}
						//System.out.println(date);
					}
					String id = mblog.get("id").getAsString();
					String regionName ="";
					if(null!=mblog.get("region_name")){
						regionName = mblog.get("region_name").getAsString();
					}
					int commentsCount = Integer.parseInt(mblog.get("comments_count").getAsString());
					//String text = mblog.get("text").getAsString();
                *//*JsonArray picArr = mblog.getAsJsonArray("pics");
                if (picArr != null) {
                    for (int j = 0; j < picArr.size(); j++) {
                        JsonObject o = picArr.get(j).getAsJsonObject();
                        JsonObject large = o.getAsJsonObject("large");
                        if (large != null) {
                            PicDetail pic = new PicDetail();
                            pic.setUrl(large.get("url").getAsString());
                            pic.setWeiboId(id);
                            pic.setText(text);
                            pic.setIndex(Integer.toString(j+1));
                            pic.setName(id+"-"+pic.getIndex());
                            pic.setCreateDate(date);
                            pic.setUid(WeiboIdToDataBase.id);
                            pics.add(pic);
                        }
                    }
                }*//*
					WeiboDetail weiboDetail = new WeiboDetail();
					weiboDetail.setWeiboId(id);
					weiboDetail.setText(text);
					weiboDetail.setCreateDate(date);
					weiboDetail.setUid(WeiboIdToDataBase.id);
					weiboDetail.setRegionName(regionName);
					weiboDetail.setCommentsCount(commentsCount);
					weiboDetail.setCreateTime(new Date());
					pics.add(weiboDetail);
				}
			}
			//开始处理图片
        *//*switch (WeiboIdToDataBase.dataMode){
            case 1:
                if(page==1){
                    createFolder(containerid);
                }
                CountDownLatch downLatch = new CountDownLatch(pics.size());
                ExecutorService executor = Executors.newFixedThreadPool(5);
                for(int i=0;i<pics.size();i++){
                    executor.submit(new ImageDownloadTask(page,downLatch, i, pics.get(i)));
                }
                insertData(pics);
            case 2:
                insertData(pics);
            case 3:
                if(page==1){
                    createFolder(containerid);
                }
                CountDownLatch downLatch2 = new CountDownLatch(pics.size());
                ExecutorService executor2 = Executors.newFixedThreadPool(5);
                for(int i=0;i<pics.size();i++){
                    executor2.submit(new ImageDownloadTask(page,downLatch2, i, pics.get(i)));
                }
        }*//*
			//log.info("过滤后大小"+pics.size());
			//插入数据
			insertData(pics);
			result.put("since_id",since_id);
			result.put("sum",array.size());
		}

		return result;
	}*/


}